#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pymysql
import schedule
import codecs
import csv
import time
import json

import urllib.request
import re
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

kkk = 'http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery1124007290087290738745_1543558330170&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCOIATC&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._A&st=(ChangePercent)&sr=-1&p=1&ps=4000&_=1543558330171'

def isn(float_num):
    value = re.compile(r'^[-+]?[0-9]+\.[0-9]+$')

    result = value.match(float_num)
    if result:
        return True
    else:
        return False

def insertdata():

    strtime = datetime.datetime.now().strftime('%H-%M')
    h = int(strtime.split('-')[0])
    m = int(strtime.split('-')[1])
    if h==9 and m<25:
        return
    if h==11 and m>35:
        return
    if h==12 and m<55:
        return
    if h==15 and m<5:
        return
    if h==16:
        return



    url="http://api.money.126.net/data/feed/0000001,1399001,1399006,1399005,UD_SHAZ,UD_SHAP,UD_SHAD,UD_SZAZ,UD_SZAP,UD_SZAD,money.api"
    #url="http://api.money.126.net/data/feed/0000001,1399001,1399006,1399005,money.api?"
    get=urllib.request.urlopen(url).read()
    strget = str(get, encoding="utf-8")
    pos= strget.find('{')



    len1 =len(strget)
    jstr = strget[pos:len1-2]
    dictjson = json.loads(jstr)

#上证
    sseci=dictjson['0000001']['price']
    sseciud=dictjson['0000001']['updown']
    sseciudpercent=dictjson['0000001']['percent']
    ssecturnover =dictjson['0000001']['turnover']

#深证
    szsei=dictjson['1399001']['price']
    szseiud = dictjson['1399001']['updown']
    szseiudpercent = dictjson['1399001']['percent']
    szseturnover = dictjson['1399001']['turnover']
#创业
    gemi=dictjson['1399006']['price']
    gemiud = dictjson['1399006']['updown']
    gemiudpercent = dictjson['1399006']['percent']
    gemturnover = dictjson['1399006']['turnover']

#中小
    smei=dictjson['1399005']['price']
    smeiud=dictjson['1399005']['updown']
    smeiudpercent=dictjson['1399005']['percent']
    smeturnover=dictjson['1399005']['turnover']

    astockupcount=dictjson['UD_SHAZ']['count']+dictjson['UD_SZAZ']['count']
    astockequalcount=dictjson['UD_SHAP']['count']+dictjson['UD_SZAP']['count']
    astockdowncount=dictjson['UD_SHAD']['count']+dictjson['UD_SZAD']['count']

    url = "http://nufm3.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=SZ.CYB&sty=UDFN&st=z&sr=&p=&ps=&token=44c9d251add88e27b65ed86506f6e5da&cb=callback06271516314408623&callback=callback06271516314408623&_=1543466112620"
    get=urllib.request.urlopen(url).read()
    strget = str(get, encoding="utf-8")
    arrstr = strget.split(',')
    arrdata = arrstr[2].split('|')
    dictcyz={}

    gemupcount=int(arrdata[0])
    gemequalcount=int(arrdata[1])
    gemdowncount=int(arrdata[2])

    #跌

    url ='http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery112405218062054323225_1543467347330&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FPGBKI&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._BKHY&st=(ChangePercent)&sr=1&p=1&ps=5&_=1543467347358'

    get=urllib.request.urlopen(url).read()
    strget = str(get, encoding="utf-8")
    pos= strget.find('{')
    #
    len1 =len(strget)
    jstr = strget[pos:len1-1]
    aaa=jstr.replace("data", '"data"', 1);
    bbb = aaa.replace('recordsFiltered','"recordsFiltered"',1)
    Industrygains1=""

    dictjson1 = json.loads(bbb)

    industrydecline1=dictjson1['data'][0].split(',')[2]
    industrydecline2 = dictjson1['data'][1].split(',')[2]
    industrydecline3 = dictjson1['data'][2].split(',')[2]
    industrydecline4 = dictjson1['data'][3].split(',')[2]
    industrydecline5= dictjson1['data'][4].split(',')[2]



    #涨
    url ='http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery112405218062054323225_1543467347330&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FPGBKI&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._BKHY&st=(ChangePercent)&sr=-1&p=1&ps=5&_=1543467347358'
    get=urllib.request.urlopen(url).read()


    strget = str(get, encoding="utf-8")
    pos= strget.find('{')
    #
    len1 =len(strget)
    jstr = strget[pos:len1-1]
    aaa=jstr.replace("data", '"data"', 1);
    bbb = aaa.replace('recordsFiltered','"recordsFiltered"',1)

    dictjson2 = json.loads(bbb)

    Industrygains1=dictjson2['data'][0].split(',')[2]
    Industrygains2 = dictjson2['data'][1].split(',')[2]
    Industrygains3 = dictjson2['data'][2].split(',')[2]
    Industrygains4 = dictjson2['data'][3].split(',')[2]
    Industrygains5 = dictjson2['data'][4].split(',')[2]

    get = urllib.request.urlopen(kkk).read()

    strget = str(get, encoding="utf-8")
    pos = strget.find('{')
    #
    len1 = len(strget)
    jstr = strget[pos:len1 - 1]
    aaa = jstr.replace("data", '"data"', 1);
    bbb = aaa.replace('recordsFiltered', '"recordsFiltered"', 1)

    limitupcount=0
    limitdowncount =0

    dictjson3 = json.loads(bbb)
    for item in dictjson3['data']:
        arritem = item.split(',')
        name = arritem[2]
        if isn( arritem[3])==False:
            continue
        cprice = float(arritem[3])

        lprice = float(arritem[12])
        ZTPRICE =0.0
        DTPRICE =0.0
        if name[0]=='N':
            aa=0
            # ZTPRICE = float('%.2f' % (lprice*1.44))
            # DTPRICE = float('%.2f' % (lprice*float(0.56)))
        elif name[0:2]=='ST' or name[1:3]=='ST':
            ZTPRICE = float('%.2f' % (lprice*float(1.05)))
            DTPRICE = float('%.2f' % (lprice*float(0.95)))

        else:
            ZTPRICE = float('%.2f' % (lprice*float(1.1)))
            DTPRICE = float('%.2f' % (lprice*float(0.9)))
        if cprice>=ZTPRICE:
            limitupcount+=1
        if cprice <=DTPRICE:
            limitdowncount+=1










    # 连接数据库

    db = pymysql.connect(host="39.105.19.0", user="root",password="My123$ql", db="stock-demo", port=3306,charset='utf8')
    cur = db.cursor()
    sqlinsert ="insert into stockdata(sseci,sseciud,sseciudpercent,ssecturnover,szsei,szseiud,szseiudpercent,szseturnover,gemi,gemiud ,gemiudpercent,gemturnover,smei,smeiud,smeiudpercent,smeturnover,Industrygains1,Industrygains2 ,Industrygains3,Industrygains4 ,Industrygains5  ,industrydecline1 ,industrydecline2 ,industrydecline3 ,industrydecline4 ,industrydecline5 ,astockupcount  ,astockequalcount ,astockdowncount  ,gemupcount,gemequalcount ,gemdowncount ,limitupcount,limitdowncount)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

    #cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
    try:
        cur.execute(sqlinsert,(sseci                 ,\
sseciud               ,\
sseciudpercent        ,\
ssecturnover          ,\
szsei                 ,\
szseiud               ,\
szseiudpercent        ,\
szseturnover          ,\
gemi                  ,\
gemiud                ,\
gemiudpercent         ,\
gemturnover           ,\
smei                  ,\
smeiud                ,\
smeiudpercent         ,\
smeturnover           ,\
Industrygains1        ,\
Industrygains2        ,\
Industrygains3        ,\
Industrygains4        ,\
Industrygains5        ,\
industrydecline1      ,\
industrydecline2      ,\
industrydecline3      ,\
industrydecline4      ,\
industrydecline5      ,\
astockupcount         ,\
astockequalcount      ,\
astockdowncount       ,\
gemupcount            ,\
gemequalcount         ,\
gemdowncount          ,\
limitupcount          ,\
limitdowncount        \

))
        db.commit()
    except:
        db.rollback()
    cur.close()
    db.close()


def main():
    #9: 30 - 11:30，下午时段13: 00 - 15:00




    sched = BlockingScheduler()
    sched.add_job(insertdata, 'cron', day_of_week='mon-fri', hour ='9-12,13-18', minute='*/2')
    sched.start()



    #
    # schedule.every().monday.at("9:25").do(insertdata)
    # schedule.every().tuesday.at("9:25").do(insertdata)
    # schedule.every().wednesday.at("9:25").do(insertdata)
    # schedule.every().thursday.at("9:25").do(insertdata)
    # schedule.every().friday.at("9:25").do(insertdata)
    #
    # schedule.every().wednesday.at("9:25").do(insertdata)
    #
    # while True:
    #     schedule.run_pending()
    #     time.sleep(10)
if __name__ == '__main__':
  main()
